import React, { Component } from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  Dimensions,
  TextInput,
  Button,
  TouchableOpacity,
  AsyncStorage
} from 'react-native'
import {
  Form,
  Item, 
  Input, 
  Label,
  Icon,
  AnimatedButton,
  ListItem,
  CheckBox,
  Body,
  Toast
} from 'native-base'
import {NavigationActions} from 'react-navigation'
import _ from 'lodash'

const { width, height } = Dimensions.get("window")

const background = require("./login1_bg.png")
const mark = require("./login1_mark.png")

export default class LoginScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      phoneError:false,
      passwordError:false,
      phone:null,
      password:null,
      phoneSuccess:false,
      passwordSuccess:false,
      remeberLogin:false,
      sessionid:null,
    }
    this.remeberLogin=this.remeberLogin.bind(this)
    this.signIn=this.signIn.bind(this)
    this.signUp=this.signUp.bind(this)
  }
  componentWillMount() {
      AsyncStorage.getItem('user',((error,result)=>{
        if(result!=null){
          let user=JSON.parse(result);
          this.setState({
            phone: user.phone,
            password: user.passward,
            remeberLogin:user.remeberLogin
          })
        }
      }));
  }
  remeberLogin(e){
    this.setState({
      remeberLogin:!this.state.remeberLogin
    })
  }
  signIn(){
    if(_.isNil(this.state.phone)||_.isNil(this.state.password)){
      Toast.show({
        text: '手机号或者密码输入格式有问题！',
        position: 'top',
        duration: 2000
      });
    }else{
      fetch("http://172.24.10.175/workout/api.php/login",{
        method:'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `tel=${this.state.phone}&password=${this.state.password}`
      }).then( (response) =>   response.json() ).then((data)=>{
          if(data.error=="用户名或密码不正确"){
            Toast.show({
              text: '手机号或者密码输入不正确',
              position: 'top',
              duration: 2000
            });
          }else{
            this.props.navigation.navigate( "Layout",{ params:  "Layout" })
               if(this.state.remeberLogin){
                let user={
                  phone:this.state.phone,
                  passward:this.state.password,
                  remeberLogin:this.state.remeberLogin,
                  users: data
                }
                AsyncStorage.setItem('user',JSON.stringify(user)).then(()=>{
                  Toast.show({
                    text: '登录成功!',
                    position: 'top',
                    duration:2000
                  });
                })
              }
          }
         
        }).catch((err)=>{
          console.log('error111111',err)
        })
    }
  }
  signUp(){
    const resetActions = NavigationActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({routeName: 'SignupView'})]
    });
    this.props.navigation.dispatch(resetActions);
  }
 
  render() {
    return (
      <View style={styles.container}>
        <Image source={background} style={styles.background} resizeMode="cover">
          <View style={styles.markWrap}>
            <Image source={mark} style={styles.mark} resizeMode="contain" />
          </View>
          <View style={styles.wrapper}>
          <Form>
            <Item error={this.state.phoneError} success={this.state.phoneSuccess} fixedLabel>
              <Icon active name='ios-phone-portrait' />
              <Input keyboardType="numeric" value={this.state.phone} placeholder='phone' onChangeText={(e)=>{
                if(e.length!=11){
                  this.setState({
                    phoneError:true,
                    phoneSuccess:false,
                    phone:null
                  })
                }else{
                  this.setState({
                    phoneError:false,
                    phone:e,
                    phoneSuccess:true
                  })
                }
              }}/>
              {this.state.phoneError==true?<Icon name='close-circle' />:(this.state.phoneSuccess==true?<Icon name='checkmark-circle' />:null)}
            </Item>
            <Item error={this.state.passwordError} success={this.state.passwordSuccess} fixedLabel last>
              <Icon active name='key'/>
              <Input keyboardType="numeric" value={this.state.password} secureTextEntry={true} placeholder="password" onChangeText={(e)=>{
                if(e.length<3||e.length>6){
                  this.setState({
                    passwordError:true,
                    passwordSuccess:false,
                    password:null
                  })
                }else{
                  this.setState({
                    password:e,
                    passwordSuccess:true,
                    passwordError:false
                  })
                }
              }}/>
              {this.state.passwordError==true?<Icon name='close-circle' />:(this.state.passwordSuccess==true?<Icon name='checkmark-circle' />:null)}
            </Item>

            <ListItem style={{backgroundColor: "transparent"}}>
              <CheckBox checked={this.state.remeberLogin} onPress={this.remeberLogin} style={{marginRight:15}} success />
              <Body>
                <Text>remember password?</Text>
              </Body>
            </ListItem>
          </Form>
            <TouchableOpacity activeOpacity={.5}>
              <View>
                <Text style={styles.forgotPasswordText}>Forgot Password?</Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity activeOpacity={.5}>
              <View style={styles.button}>
                <Text style={styles.buttonText} onPress={this.signIn}>Sign In</Text>
              </View>
            </TouchableOpacity>
          </View>
          <View style={styles.container}>
            <View style={styles.signupWrap}>
              <Text style={styles.accountText} onPress={this.signup}>Don't have an account?</Text>
              <TouchableOpacity activeOpacity={.5}>
                <View>
                  <Text style={styles.signupLinkText} onPress={this.signUp}>Sign Up</Text>
                </View>
              </TouchableOpacity>
            </View>
          </View>
        </Image>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  markWrap: {
    flex: 1,
    paddingVertical: 30,
  },
  mark: {
    width: null,
    height: null,
    flex: 1,
  },
  background: {
    width,
    height,
  },
  wrapper: {
    paddingVertical: 30,
  },
  inputWrap: {
    flexDirection: "row",
    marginVertical: 10,
    height: 40,
  },
  iconWrap: {
    paddingHorizontal: 7,
    alignItems: "center",
    justifyContent: "center",
  },
  icon: {
    height: 20,
    width: 20,
  },
  input: {
    flex: 1,
    paddingHorizontal: 10,
  },
  button: {
    backgroundColor: "#FF3366",
    paddingVertical: 20,
    alignItems: "center",
    justifyContent: "center",
    marginTop: 30,
  },
  buttonText: {
    color: "#FFF",
    fontSize: 18,
  },
  forgotPasswordText: {
    color: "#D8D8D8",
    backgroundColor: "transparent",
    textAlign: "right",
    paddingRight: 15,
  },
  signupWrap: {
    backgroundColor: "transparent",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
  },
  accountText: {
    color: "#D8D8D8"
  },
  signupLinkText: {
    color: "#FFF",
    marginLeft: 5,
  }
});
